package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.KHUtil
import groovy.json.StringEscapeUtils
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * E家安康-承保结果回写接口
 * 陶豪
 */
public  class apiInsureResultsMsg implements  ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiInsureResultsMsg.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        //初始化返回参数
        JSONObject result = new JSONObject();

        //获取接口调用方式及参数
        String GetMethod = httpServletRequest.getMethod();
        log.debug("[GetMethod]:" + GetMethod);

        String inData = "";
        if (GetMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数：]" + inData);

        }
        log.debug("[调用请求信息：]" + inData)

        if (KHUtil.isNull(inData)) {
            log.debug("入参为空-无法完成操作！");
            result.put("code", -2);
            result.put("message", "入参为空-无法完成操作！");
          //  def insertSQL2="insert into fcqt_dm_ifc_log_new(id,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'apiInsureResultsMsg'," + inData.toString() + "," + result.toString() + ",sysdate,sysdate)";
           // eliteBean.update(insertSQL2,'dataSource');
            return result.toString();
        }


        try {
            //解析Json
            String newJson=org.apache.commons.lang.StringEscapeUtils.unescapeHtml(inData);

            JSONObject inJson = JSONObject.fromObject(newJson);
            def orderNo = GetJV(inJson,"orderNo");//合作方订单申请号，系统做幂等校验
            def agencyCode = GetJV(inJson,"agencyCode");//商户号
            def productCode = GetJV(inJson,"productCode");//产品代码
            def businessType = GetJV(inJson,"businessType") ;//业务类型


            def transTime = GetJV(inJson,"transTime");//发送时间
            def policyNo =  GetJV(inJson,"policyNo");//保单号
            def policyUrl = GetJV(inJson,"policyUrl");//电子保单URL
            def batchProposalNo=GetJV(inJson,"batchProposalNo")//组合产品ID
            JSONArray batcharr
            //判断是否是组合产品
            if(businessType.equals("policyBatchResult")){
                batcharr =inJson.getJSONArray("policys");
                //校验参数是否必填
                if (    KHUtil.isNull(orderNo) ||
                        KHUtil.isNull(agencyCode) ||
                        KHUtil.isNull(productCode) ||
                        KHUtil.isNull(transTime)||
                        KHUtil.isNull(businessType)||
                        KHUtil.isNull(batchProposalNo)
                ){
                    log.debug("请求入参为空-请检查请求报文！");
                    result.put("code", -2)
                    result.put("message", "请求入参为空-请检查请求报文！")
                    def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiInsureResultsMsg','" + inData.toString() + "','" + result.toString() + "',sysdate,sysdate)";
                    eliteBean.update(insertSQL2,'dataSource');
                    return result.toString();
                }
            }else{
            //校验参数是否必填
            if (    KHUtil.isNull(orderNo) ||
                    KHUtil.isNull(agencyCode) ||
                    KHUtil.isNull(productCode) ||
                    KHUtil.isNull(policyUrl) ||
                    KHUtil.isNull(policyNo)||
                    KHUtil.isNull(transTime)||
                    KHUtil.isNull(businessType)
            ) {
                log.debug("请求入参为空-请检查请求报文！");
                result.put("code", -2)
                result.put("message", "请求入参为空-请检查请求报文！")
                def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiInsureResultsMsg','" + inData.toString() + "','" + result.toString() + "',sysdate,sysdate)";
                eliteBean.update(insertSQL2,'dataSource');
                return result.toString();
            }
            }
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            //查询订单号是否已经在电销存在

            String dealSql = "Select orderNo from EFAMILYINFORMATION where orderNo='" + orderNo + "'";
            def dealList = eliteBean.chaxun_sql(dealSql, "dataSource");
            //存在则修改
            if (dealList.size() > 0) {
                if(businessType.equals("policyBatchResult")){
                    String str="";
                    for (int b=0;b<batcharr.size();b++){
                        JSONObject dataJson=batcharr.getJSONObject(b);
                        String policyNo1=GetJV(dataJson,"policyNo");
                        String proposalNo1=GetJV(dataJson,"proposalNo");
                        String policyUrl1=GetJV(dataJson,"policyUrl");
                        str+=policyNo1.toString()+",";
                        String insertSql='''
                                  UPDATE 
                                 E_INSURERESULT_LIST
                                 SET 
                                 BATCHPROPOSALNO=?,
                                 POLICYNO=?,
                                 POLICYURL=?,
                                 UPDATEDDATE=sysdate
                                 WHERE 
                                 PROPOSALNO=?
                                 ''';

                        jt.update(insertSql,batchProposalNo,policyNo1,policyUrl1,proposalNo1);
                          }

                    if (str.length()>0){

                        str=str.substring(0,str.length()-1);

                    }


                    //更新历史表
                    String updateSql = '''
                                  Update
                                 EFAMILYINFORMATION
                                Set 
                                policyNo= ?,
                                policyUrl='ZHCP'
                                where ORDERNO=? 
                                 ''';

                    jt.update(updateSql, str, orderNo);

                }else{
                //修改之前,先插入历史表
                String insertHisSql = '''
                                INSERT INTO
                                 EFAMILYINSURE_HIS
                                (HIS_GUID,REC_GUID,
                                ORDERNO,
                                AGENCYCODE,
                                PRODUCTCODE,
                                BUSINESSTYPE,
                                TRANSTIME,
                                policyNo,
                                policyUrl
                                )values
                                (
                                sysguid,
                                sysguid,                                
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?
                                )
                                     ''';
                jt.update(insertHisSql, orderNo,agencyCode,productCode,businessType,transTime,policyNo,policyUrl);

                //更新历史表
                String updateSql = '''
                                  Update
                                 EFAMILYINFORMATION
                                Set 
                                policyNo= ?,
                                policyUrl= ?
                                where ORDERNO=? 
                                 ''';

                jt.update(updateSql, policyNo, policyUrl, orderNo);

                }

            } else {
                log.debug("请求失败-在电销系统找不到改单号!");
                result.put("code",-1)
                result.put("message","请求失败-在电销系统找不到该单号!")
                def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiInsureResultsMsg','" + inData.toString() + "','" + result.toString() + "',sysdate,sysdate)";
                eliteBean.update(insertSQL2,'dataSource');
                return  result.toString();

            }
            result.put("code", 1);
            result.put("message", "处理成功！");

            def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiInsureResultsMsg','" + inData.toString() + "','" + result.toString() + "',sysdate,sysdate)";
           eliteBean.update(insertSQL2,'dataSource');
        } catch (Exception e) {
            result.put("code", -1);
            result.put("message", e.getMessage());
            def insertSQL2="insert into fcqt_dm_ifc_log_new(id,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'apiInsureResultsMsg','" + inData.toString() + "','" + result.toString() + "',sysdate,sysdate)";
            eliteBean.update(insertSQL2,'dataSource');
        }
        return result;
    }

    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

}